package com.common.frame.utils;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;


import java.io.File;
import java.lang.reflect.Method;

/**
 * SystemUtils
 **/
public class SystemUtils {

    public static String getMetaData(Context context,String key) {
        String value = null;
        try {
            ApplicationInfo appInfo = context.getPackageManager().getApplicationInfo(
                    context.getPackageName(), PackageManager.GET_META_DATA);
            value = appInfo.metaData.getString(key);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        if (value==null) value="";
        return value;
    }

    public static String getIMEI(Context context){
        String imei = "";
        try {
            TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            if(Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP){
                imei = tm.getDeviceId();
            }else {
                Method method = tm.getClass().getMethod("getImei");
                method.setAccessible(true);
                imei = (String) method.invoke(tm);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return imei;
    }

    public static int getStatusBarHeight(Context context) {
        int height = 0;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen",
                    "android");
            if (resourceId > 0) {
                height = context.getResources().getDimensionPixelSize(resourceId);
            }
        }
        return height;
    }

    public static int getNavigationBarHeight(Context context) {
        int height = 0;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            int resourceId = context.getResources().getIdentifier("navigation_bar_height", "dimen",
                    "android");
            if (resourceId > 0) {
                height = context.getResources().getDimensionPixelSize(resourceId);
            }
        }
        return height;
    }

    public static boolean isNavigationBarShow(Context context){
        //判断手机底部是否支持导航栏显示
        boolean haveNavigationBar = checkDeviceHasNavigationBar(context);
        if (haveNavigationBar) {
            if (Build.VERSION.SDK_INT >= 17) {
                String brand = Build.BRAND;
                String mDeviceInfo;
                if (brand.equalsIgnoreCase("HUAWEI")) {
                    mDeviceInfo = "navigationbar_is_min";
                } else if (brand.equalsIgnoreCase("XIAOMI")) {
                    mDeviceInfo = "force_fsg_nav_bar";
                } else if (brand.equalsIgnoreCase("VIVO")) {
                    mDeviceInfo = "navigation_gesture_on";
                } else if (brand.equalsIgnoreCase("OPPO")) {
                    mDeviceInfo = "navigation_gesture_on";
                } else {
                    mDeviceInfo = "navigationbar_is_min";
                }

                if (Settings.Global.getInt(context.getContentResolver(), mDeviceInfo, 0) == 0) {
                    return true;
                }
            }
        }
        return false;
    }

    private static boolean checkDeviceHasNavigationBar(Context context) {
        boolean hasNavigationBar = false;
        Resources rs = context.getResources();
        int id = rs.getIdentifier("config_showNavigationBar", "bool", "android");
        if (id > 0) {
            hasNavigationBar = rs.getBoolean(id);
        }
        try {
            Class systemPropertiesClass = Class.forName("android.os.SystemProperties");
            Method m = systemPropertiesClass.getMethod("get", String.class);
            String navBarOverride = (String) m.invoke(systemPropertiesClass, "qemu.hw.mainkeys");
            if ("1".equals(navBarOverride)) {
                hasNavigationBar = false;
            } else if ("0".equals(navBarOverride)) {
                hasNavigationBar = true;
            }
        } catch (Exception e) {

        }
        return hasNavigationBar;
    }

    public static int getMipmapResource(String imageName){
        return getResourceIdFromName(AppGlobals.getApplication(), "mipmap", imageName);
    }

    public static int getColorResource(String colorName){
        return getResourceIdFromName(AppGlobals.getApplication(), "color", colorName);
    }

    public static int getResourceIdFromName(Context context, String fileName, String resName){
        //如果没有找到,将会返回0
        return context.getResources().getIdentifier(resName, fileName, context.getPackageName());
    }

    public static int getVersionCode(Context context){
        PackageManager packageManager=context.getPackageManager();
        PackageInfo packageInfo;
        int versionCode=0;
        try {
            packageInfo=packageManager.getPackageInfo(context.getPackageName(),0);
            versionCode=packageInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }

    public static String getVersionName(Context context){
        PackageManager packageManager=context.getPackageManager();
        PackageInfo packageInfo;
        String versionCode="";
        try {
            packageInfo=packageManager.getPackageInfo(context.getPackageName(),0);
            versionCode=packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }


    /**
     *  向系统媒体库中立即插入媒体资源。
     */
    public static void scanFile(Context context, String filePath, boolean isImage){
        String mimeType = isImage ? "image/jpeg" : "video/mp4";
        MediaScannerConnection.scanFile(context, new String[]{filePath}, new String[]{mimeType}, null);
    }

    /**
     * 跳转到设置界面。
     */
    public static void gotoAppSettingPage(Context context) {
        Intent mIntent = new Intent();
        mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 9) {
            mIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            mIntent.setData(Uri.fromParts("package", context.getPackageName(), null));
        } else if (Build.VERSION.SDK_INT <= 8) {
            mIntent.setAction(Intent.ACTION_VIEW);
            mIntent.setClassName("com.android.settings", "com.android.setting.InstalledAppDetails");
            mIntent.putExtra("com.android.settings.ApplicationPkgName", context.getPackageName());
        }
        context.startActivity(mIntent);
    }

    /**
     * 安装软件
     */
    public static void installApk(Context context, File file) {
        Intent install = new Intent(Intent.ACTION_VIEW);
        install.setAction("android.intent.action.VIEW");
        install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        install.setDataAndType(FileUtils.getFileUriByPathToN(file), "application/vnd.android.package-archive");
        context.startActivity(install);
    }

    /**
     * 获取系统剪贴板内容
     */
    public static String getClipContent() {
        ClipboardManager manager = (ClipboardManager) AppGlobals.getApplication().getSystemService(Context.CLIPBOARD_SERVICE);
        if (manager != null) {
            if (manager.hasPrimaryClip() && manager.getPrimaryClip().getItemCount() > 0) {
                ClipData primaryClip = manager.getPrimaryClip();
                if ("RoomIdData".equals(primaryClip.getDescription().getLabel())){
                    return "";
                }
                CharSequence addedText = primaryClip.getItemAt(0).getText();
                String addedTextString = String.valueOf(addedText);
                if (!TextUtils.isEmpty(addedTextString)) {
                    return addedTextString;
                }
            }
        }
        return "";
    }

    /**
     * 清空剪切板
     */
    public static void clearClipContent() {
        ClipboardManager manager = (ClipboardManager) AppGlobals.getApplication().getSystemService(Context.CLIPBOARD_SERVICE);
        if (manager != null) {
            try {
                manager.setPrimaryClip(manager.getPrimaryClip());
                manager.setPrimaryClip(ClipData.newPlainText("", ""));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void copyContent2Clip(String label, String content){
        ClipboardManager manager = (ClipboardManager) AppGlobals.getApplication().getSystemService(Context.CLIPBOARD_SERVICE);
        if (manager != null) {
            ClipData mClipData = ClipData.newPlainText(label, content);
            manager.setPrimaryClip(mClipData);
        }
    }

    public static void sendHatUpdateBroadcast(Context context, boolean boot) {
        //头盔启动发送广播，触发升级。
        Intent sendIntent = new Intent("com.bygz.hat.apk");
        sendIntent.putExtra("boot", boot);
        sendIntent.setComponent(new ComponentName("com.byjz.hatinstall", "com.byjz.hatinstall.BootReceiver"));
        context.sendBroadcast(sendIntent);
    }
}
